package com.ruoyi.system.utils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

@Slf4j
public class EnumUtil {

    private static final String CODE_METHOD = "getCode";
    private static final String DESC_METHOD = "getDesc";

    /**
     * 根据CODE获取描述
     *
     * @param enumClass
     * @param code
     * @return
     */
    public static String getDescByCode(Class<? extends Enum> enumClass, String code) {

        Enum em = getEnumByCode(enumClass, code);
        if (em == null) {
            return null;
        }

        try {
            Method descMethod = enumClass.getMethod(DESC_METHOD);
            return Objects.toString(descMethod.invoke(em), null);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 根据Code 获取 对应枚举
     *
     * @param enumClass
     * @param code
     * @param <T>
     * @return
     */
    public static <T extends Enum> T getEnumByCode(Class<T> enumClass, String code) {
        if (!StringUtils.hasText(code)) {
            return null;
        }
        try {
            Method codeMethod = enumClass.getMethod(CODE_METHOD);
            for (T em : enumClass.getEnumConstants()) {
                if (codeMethod.invoke(em).equals(code)) {
                    return em;
                }
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        log.error("[{}]未知的code：{}", enumClass, code);
        return null;
    }

    /**
     * 校验数值 是否在对应的值集中
     * @param code
     * @param enumClass
     * @return
     */
    public static boolean isEnumValue(Object code, Class enumClass) {
        try {
            String descByCode = getDescByCode(enumClass, String.valueOf(code));
            if (!ObjectUtils.isEmpty(descByCode)) {
                return true;
            }
            return false;
        } catch (Exception e) {
            return false;
        }
    }

    /**
     * enum class 获取一个Map类型的结果集
     * @param enumClass
     * @return [ key: 字典值， value 字典描述 ]
     */
    public static Map<String, String> toMap(Class enumClass) {
        if (!enumClass.isEnum()) {
            return null;
        }

        Map<String, String> resMap = new HashMap<>();
        Object[] enumConstants = enumClass.getEnumConstants();
        for (Object item : enumConstants) {
            try {
                Method codeMethod = item.getClass().getMethod(CODE_METHOD);
                Object code = codeMethod.invoke(item);

                Method descMethod = item.getClass().getMethod(DESC_METHOD);
                Object desc = descMethod.invoke(item);

                resMap.put(String.valueOf(code), String.valueOf(desc));
            } catch (Exception e) {

            }
        }
        return resMap;
    }
}
